package com.greet.handler;

import com.greet.constant.MessageConstant;
import com.greet.enumeration.SqlExceptionType;
import com.greet.exception.BaseException;
import com.greet.result.Result;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    private SqlExceptionType getSqlErrorType(String msg){
        SqlExceptionType sqlExceptionType = SqlExceptionType.UNKOWN_ERRO;
        //字段已存在
        if (msg.contains("Duplicate entry")){
            if (msg.contains("employee.idx_username")){//用户名字段
                sqlExceptionType = SqlExceptionType.USER_HAS_CANNOT_ADD;
            }else if (msg.contains("category.idx_category_name")){//分类名字段
                sqlExceptionType = SqlExceptionType.CATEGORY_HAS_CANNOT_ADD;
            }else if (msg.contains("dish.idx_dish_name")){
                sqlExceptionType = SqlExceptionType.DISH_HAS_CANNOT_ADD;
            }else if (msg.contains("setmeal.idx_setmeal_name")){
                sqlExceptionType = SqlExceptionType.SETMEAL_HAS_CANNOT_ADD;
            }
        }

        return sqlExceptionType;
    }

    private String analyseSqlError(String msg){
        String result = new String();
        SqlExceptionType errType = getSqlErrorType(msg);
        switch (errType){
            case USER_HAS_CANNOT_ADD -> {
                result = "用户" +
                        msg.split(" ")[2].split("'")[1] +
                        "已存在";
            }
            case CATEGORY_HAS_CANNOT_ADD -> {
                result = "分类" +
                        msg.split(" ")[2].split("'")[1] +
                        "已存在";
            }
            case DISH_HAS_CANNOT_ADD -> {
                result = "菜品" +
                        msg.split(" ")[2].split("'")[1] +
                        "已存在";
            }
            case SETMEAL_HAS_CANNOT_ADD -> {
                result = "套餐" +
                        msg.split(" ")[2].split("'")[1] +
                        "已存在";
            }
            case UNKOWN_ERRO -> {
                result = "未知错误";
            }
            default -> {}
        }
        return result;
    }

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'zhangsan' for key 'employee.idx_username
        //重复的键值对
        String msg = ex.getMessage();
        log.error("异常信息：{}", msg);
        return Result.error(analyseSqlError(msg));
    }

    @ExceptionHandler
    public Result exceptionHandler(ExpiredJwtException ex){
        if (ex.getMessage().contains("JWT expired")){
            log.error(MessageConstant.USER_NOT_LOGIN);
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

}
